/**
 * 防抖
 * @param fn 回调函数
 * @param wait 防抖间隔 默认 100
 * @param immediate ture：执行第一次  false: 执行最后一次
 * @returns {(function(): void)|*}
 */
export const debounce = (fn, wait = 100, immediate = false) => {
  let timer, startTimeStamp = 0
  let context, args

  let run = (timerInterval) => {
    timer = setTimeout(() => {
      let now = (new Date()).getTime()
      let interval = now - startTimeStamp
      if(interval < timerInterval) {
        startTimeStamp = now
        run(wait - interval)
      }else{
        if(!immediate) {
          fn.apply(context, args)
        }
        clearTimeout(timer)
        timer = null
      }

    }, timerInterval)
  }

  return function () {
    context = this
    args = arguments
    startTimeStamp = (new Date()).getTime()

    if(!timer) {
      if(immediate) {
        fn.apply(context, args)
      }
      run(wait)
    }

  }
}

/**
 * 节流
 * @param fn 回调函数
 * @param wait 节流间隔 默认 100
 * @param immediate 第一次是否执行
 * @returns {(function(): void)|*}
 */
export const throttling = (fn, wait, immediate) => {
  let timer = 0
  let context, args

  let run = () => {
    timer = setTimeout(() => {
      if(!immediate) {
        fn.apply(context, args)
      }
      clearTimeout(timer)
      timer = null
    }, wait)
  }

  return function () {
    context = this
    args = arguments
    if(!timer) {
      if(immediate) {
        fn.apply(context, args)
      }
      run()
    }else{
      console.log('throttle, ignore')
    }
  }

}

/**
 * @description base64URL转文件
 * @param base64URL base64数据
 * @param filename 文件名（必须带后缀名，如.jpg,.png）
 * @returns {File}
 */
export const base64URLtoFile = (base64URL, filename) => {
  const arr = base64URL.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}

/**
 * @description 下载文件
 * @param url 文件流地址
 * @param name 下载文件名
 */
export const downloadFile = (url, name) => {
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('name', name)
  a.setAttribute('href', url)
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}
